<template>
  <div class="monthly-sales-page">
    <!-- 顶部信息卡片 -->
    <div class="info-card">
      <div class="info-content">
        <!-- 左侧图片 -->
        <div class="info-image">
          <img src="/banner2.jpg" alt="2020年每月销售分析" />
        </div>
        <!-- 右侧文字 -->
        <div class="info-text">
          <h2>📊 2020年每月销售情况分析</h2>
          <p class="desc">
            本图表展示了2020年每月的商品销量和总销售额。柱状图表示每月销售数量，折线图表示每月销售总额，  
            可直观对比销售波动和销售趋势。通过该分析，可帮助企业了解销售高峰月份和销售低谷，优化库存和营销策略。
          </p>
        </div>
      </div>
    </div>

    <!-- 图表卡片 -->
    <div class="chart-card">
      <div class="chart-container" ref="chartRef"></div>
      <p class="note">提示：柱形图表示销量（件），折线图表示总销售额（元）</p>
    </div>

    <!-- 下载按钮 -->
    <div class="download-wrapper">
      <button class="download-btn" @click="downloadChart">下载图表文件</button>
    </div>

    <!-- 页面底部 Footer -->
    <FooterInfo />
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import axios from 'axios'
import FooterInfo from '../components/FooterInfo.vue'

const chartRef = ref(null)
let chartInstance = null
const chartData = ref([])

// 获取每月销售数据
async function fetchMonthlySales() {
  try {
    const res = await axios.get('http://localhost:8080/sales/monthly')
    if (res.data.code === 200) {
      // 按月份排序
      chartData.value = res.data.data.sort((a, b) => new Date(a.time) - new Date(b.time))
      updateChart()
    } else {
      alert('获取每月销售数据失败')
    }
  } catch (err) {
    console.error(err)
    alert('请求接口失败，请检查网络或接口地址')
  }
}

// 初始化图表
onMounted(async () => {
  await nextTick()
  const el = chartRef.value
  if (!el) return

  chartInstance = echarts.init(el)
  chartInstance.setOption({
    tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
    legend: { data: ['销量', '总销售额'], top: '5%', textStyle: { color: '#333' } },
    xAxis: { type: 'category', data: [] },
    yAxis: [
      { type: 'value', name: '销量 (件)', position: 'left' },
      { type: 'value', name: '总销售额 (元)', position: 'right' }
    ],
    series: []
  })

  await fetchMonthlySales()
})

// 更新图表数据
function updateChart() {
  if (!chartInstance || !chartData.value.length) return
  chartInstance.setOption({
    xAxis: { data: chartData.value.map(d => d.time) },
    series: [
      {
        name: '销量',
        type: 'bar',
        data: chartData.value.map(d => d.salesCount),
        itemStyle: { color: '#4a90e2' },
        yAxisIndex: 0,
        barCategoryGap: '20%'
      },
      {
        name: '总销售额',
        type: 'line',
        data: chartData.value.map(d => d.totalSales),
        itemStyle: { color: '#ff6f61' },
        yAxisIndex: 1
      }
    ]
  })
}

// 下载图表
function downloadChart() {
  if (!chartInstance) return
  const url = chartInstance.getDataURL({ type: 'png', pixelRatio: 2, backgroundColor: '#fff' })
  const link = document.createElement('a')
  link.href = url
  link.download = 'monthly-sales-chart.png'
  link.click()
}
</script>

<style scoped>
.monthly-sales-page {
  max-width: 1000px;
  margin: 40px auto;
  font-family: 'Segoe UI', sans-serif;
}

/* 顶部信息卡片 */
.info-card {
  background: #fff;
  padding: 25px 30px;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.05);
  margin-bottom: 25px;
}

.info-content {
  display: flex;
  align-items: flex-start;
  gap: 20px;
}

.info-image img {
  width: 240px;
  height: auto;
  border-radius: 8px;
  object-fit: cover;
  margin-top: 70px;
}

.info-text {
  flex: 1;
}

.info-text h2 {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 12px;
  color: #333;
}

.info-text .desc {
  font-size: 15px;
  color: #555;
  line-height: 1.8;
  text-align: justify;
}

/* 图表卡片 */
.chart-card {
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.05);
  padding: 20px;
  margin-bottom: 20px;
}

.chart-container {
  width: 100%;
  height: 400px;
}

.note {
  text-align: center;
  font-size: 13px;
  color: #888;
  margin-top: 10px;
}

/* 下载按钮 */
.download-wrapper {
  text-align: center;
  margin-bottom: 30px;
}

.download-btn {
  background: #ff7f50;
  color: #fff;
  padding: 10px 22px;
  border: none;
  border-radius: 6px;
  font-size: 15px;
  cursor: pointer;
  transition: background 0.3s;
}

.download-btn:hover {
  background: #ff6333;
}
</style>
